package com.ruoyi.web.controller.okr;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.OkrCycle;
import com.ruoyi.system.domain.OkrInfo;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.domain.resultMapper.OkrAnalysisResult;
import com.ruoyi.system.service.IOkrCycleService;
import com.ruoyi.system.service.IOkrInfoService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Bruce on 2021/9/12 0:48
 **/
@Controller
@RequestMapping("/analysis")
public class MyOkrAnalysisController extends BaseController {

    @Autowired
    private IOkrInfoService okrInfoService;

    @Autowired
    private IOkrCycleService okrCycleService;

    @Autowired
    private ISysUserService userService;

    String prefix = "okr";

    @RequestMapping("")
    public String show(ModelMap mmap){
        List<OkrCycle> list = okrCycleService.selectOkrCycleList(new OkrCycle());
        mmap.put("cycleList", list);
        return prefix + "/okrAnalysis";
    }

    @RequestMapping("/list")
    @ResponseBody
    public TableDataInfo queryOkrAnalysis(OkrInfo okrInfo, ModelMap mmap){
        SysUser user = ShiroUtils.getSysUser();
        Long cycleId = okrInfo.getCycleId();
        if (cycleId == null){
            List<OkrCycle> useCycleList = okrCycleService.selectOkrUseCycleList();
            cycleId = useCycleList.get(0).getId();
        }
        List<OkrAnalysisResult> okrInfos = okrInfoService.queryOkrInDept(user.getDeptId(), cycleId, 0L);
        List<OkrAnalysisResult> infos = new ArrayList<>();
        //部门下的目标与关键结果进度差值大于15
        for (OkrAnalysisResult o : okrInfos){
            OkrInfo obj = okrInfoService.selectOkrInfoById(o.getOkrId());
            List<OkrInfo> krs = okrInfoService.selectOkrInfoListByParentId(obj);
            for (OkrInfo r : krs){
                if (Math.abs(Double.parseDouble(obj.getProcess()) - Double.parseDouble(r.getProcess())) >= 15.0){
                    OkrAnalysisResult analysis = new OkrAnalysisResult();
                    analysis.setContent(obj.getContent());
                    SysUser u = userService.selectUserById(obj.getUserId());
                    analysis.setUserName(u.getUserName());
                    analysis.setUserId(u.getUserId());
                    analysis.setProcess(obj.getProcess());
                    analysis.setOkrId(obj.getId());
                    infos.add(analysis);
                    break;
                }
            }
        }
        return getDataTable(infos);
    }


}
